import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:video_player/video_player.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/features/skills/viewmodels/video_player_viewmodel.dart';
import 'package:vista/shared/services/tutorial_video_service.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';

/// 视频播放页面
class VideoPlayerView extends StatelessWidget {
  final String videoId;

  const VideoPlayerView({super.key, required this.videoId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<VideoPlayerViewModel>.reactive(
      viewModelBuilder:
          () =>
              VideoPlayerViewModel(getIt.get<TutorialVideoService>(), videoId)
                ..initialize(),
      // onDispose 不需要做任何事情，因为 dispose() 方法已经处理了清理
      // ViewModelBuilder 会自动调用 ViewModel 的 dispose() 方法
      builder: (context, model, child) {
        if (model.isBusy || model.video == null) {
          return Scaffold(
            body: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/my-background.png'),
                  fit: BoxFit.fill,
                ),
              ),
              child: const Center(child: CircularProgressIndicator()),
            ),
          );
        }

        return Scaffold(
          body: SizedBox.expand(
            child: Stack(
              children: [
                // 全屏视频背景
                if (!model.isDisposing) _buildVideoBackground(model),
                // 左上角返回按钮
                Positioned(
                  top: 0,
                  left: 0,
                  child: _buildBackButton(context, model),
                ),
                // 右上角举报按钮
                Positioned(
                  top: 0,
                  right: 0,
                  child: _buildReportButton(context, model),
                ),
                // 底部蒙层（视频标题信息）
                if (!model.isDisposing) _buildBottomOverlay(context, model),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建全屏视频背景
  Widget _buildVideoBackground(VideoPlayerViewModel model) {
    if (model.isDisposing || !model.isInitialized || model.controller == null) {
      return Container(
        color: Colors.black,
        child: const Center(child: CircularProgressIndicator()),
      );
    }

    final controller = model.controller!;
    final aspectRatio = controller.value.aspectRatio;

    return Positioned.fill(
      child: GestureDetector(
        onTap: () {
          if (!model.isDisposing &&
              model.isInitialized &&
              model.controller != null) {
            model.togglePlayPause();
          }
        },
        child: AspectRatio(
          aspectRatio: aspectRatio,
          child: VideoPlayer(controller),
        ),
      ),
    );
  }

  /// 构建左上角返回按钮
  Widget _buildBackButton(BuildContext context, VideoPlayerViewModel model) {
    return SafeArea(
      child: Padding(
        padding: EdgeInsets.only(left: 14.w, top: 14.h),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.3),
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: GestureDetector(
            onTap: () async {
              // 先清理视频播放器
              await model.cleanup();
              // 等待一帧，确保清理完成
              await Future.delayed(Duration.zero);
              // 然后返回
              if (context.mounted) {
                getIt.get<NavigationService>().back();
              }
            },
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: Image.asset(
                'assets/images/back.png',
                width: 24.w,
                height: 24.w,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建右上角举报按钮
  Widget _buildReportButton(BuildContext context, VideoPlayerViewModel model) {
    return SafeArea(
      child: Padding(
        padding: EdgeInsets.only(right: 14.w, top: 14.h),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.3),
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: GestureDetector(
            onTap: () async {
              await ComplainHelper.unveil(
                context,
                onComplain: (reason) async {
                  // 举报成功后删除视频
                  await model.deleteVideo();
                  if (context.mounted) {
                    getIt.get<NavigationService>().back();
                    FlashNotifier.flashSuccess('Report submitted successfully');
                  }
                },
              );
            },
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: Image.asset(
                'assets/images/report.png',
                width: 24.w,
                height: 24.w,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建底部蒙层（视频标题信息）
  Widget _buildBottomOverlay(BuildContext context, VideoPlayerViewModel model) {
    if (model.video == null) {
      return const SizedBox.shrink();
    }

    final video = model.video!;

    return Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.transparent, Colors.black.withOpacity(0.7)],
          ),
        ),
        padding: EdgeInsets.fromLTRB(14.w, 20.h, 14.w, 40.h),
        child: SafeArea(
          child: [
            // 视频标题
            Text(
              video.title,
              style: TextStyle(
                fontSize: 20.sp,
                fontFamily:
                    GoogleFonts.alegreyaSans(
                      fontWeight: FontWeight.w700,
                    ).fontFamily,
                color: Colors.white,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
        ),
      ),
    );
  }
}
